import { t } from 'i18next'
import { Alert } from '@/components/Alert'
import { CardWrap } from './style'
import { ICard } from './translator'
import { base64encode, isIE, utf16to8 } from '../../utils'
import { fetchDownLoadVrs } from '@/api/meetingSpace'

export const Card = ({
	data: { programName, programEncMode, createTime, duration, jsonPath, snapshotPath, details, streamjsonpath },
	token,
	vrsAddress,
	auth,
}: {
	data: ICard
	token: string
	vrsAddress: string
	auth: {
		play: boolean
		download: boolean
	}
}) => {
	const goToVrs = () => {
		if (details[0]?.id) {
			if (programEncMode === 2 || programEncMode === 4) {
				Alert(t('不支持播放此类型视频，加密类型视频请使用加密播放器观看。'))
			} else {
				if (jsonPath) {
					window.location.href = `${vrsAddress}/broadcasthtml.html?${base64encode(
						utf16to8(`id=${details[0].id}&live=0&sso_token=${token}`)
					)}`
				} else {
					if (isIE()) {
						window.location.href = `${vrsAddress}/broadcasthtml.html?${base64encode(
							utf16to8(`id=${details[0].id}&live=0&sso_token=${token}`)
						)}`
					} else {
						Alert(t('无法播放该视频，推荐使用IE浏览器观看'))
					}
				}
			}
		}
	}
	const download = () => {
		if (!auth.download) {
			Alert(t('无相关权限，无法下载会议录像。'))
			return
		}
		if (jsonPath) {
			fetchDownLoadVrs(streamjsonpath).then(({ data }) => {
				var reader = new FileReader()
				reader.readAsText(new Blob([data]))
				reader.onload = function () {
					var binary = this.result as string
					const data = JSON.parse(binary)
					if (data && data.proList) {
						for (const item of data.proList) {
							if (item.indexList) {
								window.open(
									`${vrsAddress}${item.indexList[0].hlsIndex}?download=1&nameencode=0&sso_token=${token}`
								)
							}
						}
					}
				}
			})
		} else {
			//老终端，只能走普通的asf路径下载
			if (details[0]?.asfPath) {
				window.open(`${details[0].asfPath}?sso_token=${token}`)
			}
		}
	}
	return (
		<CardWrap>
			<div className="card-pic" onClick={goToVrs}>
				{/* {snapshotPath && <img src={snapshotPath} alt="" />} */}
				<div className="hover-pic"></div>
				<span className="card-time">{duration}</span>
				{!jsonPath && <span className="card-ie">{t('仅支持IE浏览器')}</span>}
			</div>
			<div className="card-tips">
				<div>{createTime}</div>
				<div className="card-download" onClick={download}>
					{t('下载')}
				</div>
			</div>
			<div className="card-name" title={programName}>
				{programName}
			</div>
		</CardWrap>
	)
}
